package com.example.client_demo.common;

import com.example.client_demo.entity.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @Description:
 * @Author: mayc
 * @Date: 2019/03/14 11:47
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final String USER_INFO = "user_info";
    public static ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Clear clear = method.getAnnotation(Clear.class);
            if (clear != null) {
                return true;
            }
            // 否则检测人员信息
            HttpSession session = request.getSession();
            String attr = (String) session.getAttribute(USER_INFO);
            if (!StringUtils.isEmpty(attr)) {
                return true;
            }
            response.sendRedirect("login");
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            Method me = method.getMethod();
            if (me.getName().equals("logout")) {
                HttpSession session = request.getSession();
                String userInfo = (String) session.getAttribute(USER_INFO);
                if (!StringUtils.isEmpty(userInfo)) {
                    session.removeAttribute(USER_INFO);
                }
            }
        }
    }
}
